﻿using System;
using System.Text;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.MobileControls;
using System.Text.RegularExpressions;

namespace Shop.WapController.Controls
{
    [
        ToolboxItem(true),
        ParseChildren(true),
        PersistChildren(false),
        DefaultEvent("PageIndexChanged"),
        //ControlBuilder(typeof(DataPagerControlBuilder)),
        ToolboxData("<{0}:DataPager runat=\"server\"></{0}:DataPager>")
    ]
    public class DataPager : MobileControl, IPostBackDataHandler, IPostBackEventHandler, INamingContainer
    {
        #region event
        
        public event EventHandler<DataPagerPageEventArgs> PageIndexChanged;        

        #endregion        

        #region constant

        public const string DEFAULT_SUMMARY_FORMAT = "第 {0} 页/共 {1} 页 共 {2} 条";

        #endregion
        

        #region Properties                       
        
        private PagerNavigationItem _previousItem;
        [
            Description("前一页按钮"),
            DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
            PersistenceMode(PersistenceMode.InnerProperty)
        ]
        public PagerNavigationItem PreviousItem
        {
            get { return _previousItem; }
            set { _previousItem = value; }
        }


        private PagerNavigationItem _nextItem;
        [
            Description("后一页按钮"),
            DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
            PersistenceMode(PersistenceMode.InnerProperty)
        ]
        public PagerNavigationItem NextItem
        {
            get { return _nextItem; }
            set { _nextItem = value; }
        }

        private string _cssClass;
        [Description("分页控件样式")]
        public string CssClass
        {
            get { return _cssClass; }
            set { _cssClass = value; }
        }

        private string _summaryFormat;
        [Description("分页统计，如格式为：{0}/{1}, {0}代表当前第几页，{1}代表总页数")]
        public string SummaryFormat
        {
            get { return _summaryFormat; }
            set { _summaryFormat = value; }
        }

        private int _pageIndex;
        [Description("当前页码")]
        public int PageIndex
        {
            get { return _pageIndex; }
            set { _pageIndex = value; }
        }

        private int _pageCount;
        [Description("总页码数")]
        public int PageCount
        {
            get { return _pageCount; }
            set { _pageCount = value; }
        }

        private int _pageSize;
        [Description("每页记录数")]
        public int PageSize
        {
            get { return _pageSize; }
            set { _pageSize = value; }
        }

        private string _dataProvider;
        [Description("数据提供者")]
        public string DataProvider
        {
            get { return _dataProvider; }
            set { _dataProvider = value; }
        }

        private HtmlTextWriterTag _layout;
        [Description("控件布局")]
        public HtmlTextWriterTag Layout
        {
            get { return _layout; }
            set { _layout = value; }
        }

        private int _recordCount;
        [Description("总记录数")]
        public int RecordCount
        {
            get { return _recordCount; }
            set 
            { 
                _recordCount = value;
            }
        }

        private string _requestField;
        [Description("地址栏传递页码的参数名称")]
        public string RequestField
        {
            get { return _requestField; }
            set { _requestField = value; }
        }

        #endregion

        #region Constructor

        public DataPager()
        {
            //default layout
            _layout = HtmlTextWriterTag.Table;
            _pageIndex = 1;
        }

        public override bool Visible
        {
            get
            {
                return base.Visible;
            }
            set
            {
                if (!value)
                {
                    this.Dispose();                    
                }
            }
        }
        #endregion

        protected override void Render(HtmlTextWriter writer)
        {
            if (!string.IsNullOrEmpty(_dataProvider))
            {
                //has data provider
                Control control = this.Page.FindControl(_dataProvider);
                if (control != null)
                {
                    IPagerDataProvider dataProvider = null;
                    try
                    {
                        dataProvider = (IPagerDataProvider)control;
                    }
                    catch (InvalidCastException ex)
                    {
                        string errorMessage = "控件" + _dataProvider + "不支持" + typeof(IPagerDataProvider).FullName + "接口";
                        throw new Exception(errorMessage + ex.ToString());
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }

                    if (dataProvider != null && dataProvider.RecordCount > 0)
                    {
                        this.ComputePageCount(dataProvider.RecordCount, dataProvider.PageSize);
                    }
                    else
                    {
                        this.Visible = false;
                        return;
                    }
                }
                else
                {
                    if (this.DesignMode)
                    {
                        _pageCount = 0;
                    }
                    else
                    {
                        throw new Exception("找不到名为" + _dataProvider + "的控件。");
                    }
                }
            }

            if (_recordCount == 0)
            {
                this.Visible = false;
                return;
            }

            //compute pagecount
            this.ComputePageCount(_recordCount, _pageSize);

            //set current page
            _pageIndex = Math.Min(_pageIndex, _pageCount);
            _pageIndex = Math.Max(_pageIndex, 1);

            base.Render(writer);    //make sure call control adapter render, it will call related adatper class render function.
        }        

        #region IPostBackDataHandler 成员

        public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
        {         
            string[] values = postCollection[postDataKey].Split(new char[] { ',' });

            if (values.Length >= 2)
            {
                _pageIndex = Convert.ToInt32(values[0]);
                _pageCount = Convert.ToInt32(values[1]);
            }

            return false;   //prevent raisepostdatachangeevent
        }

        public void RaisePostDataChangedEvent()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Private method

        public void ComputePageCount(int recordCount, int pageSize)
        {
            if (_pageSize < 1)
            {
                _pageSize = 1;
            }

            if (pageSize < recordCount)
            {
                if (_recordCount % _pageSize == 0)
                {
                    _pageCount = (int)Math.Floor((double)(_recordCount / _pageSize));
                }
                else
                {
                    _pageCount = (int)Math.Floor((double)(_recordCount / _pageSize)) + 1;
                }
            }
            else
            {
                _pageCount = 1;
            }
        }

        #endregion

        #region IPostBackEventHandler 成员

        public void RaisePostBackEvent(string eventArgument)
        {
            int newPageIndex = Convert.ToInt32(eventArgument);
            _pageIndex = newPageIndex;

            if (this.PageIndexChanged != null)
            {                
                DataPagerPageEventArgs e = new DataPagerPageEventArgs(newPageIndex);
                this.PageIndexChanged(this, e);
            }
        }

        #endregion
    }

    public class DataPagerPageEventArgs : EventArgs
    {
        private int _newPageIndex;

        public int NewPageIndex
        {
            get { return _newPageIndex; }
            set { _newPageIndex = value; }
        }

        public DataPagerPageEventArgs(int newPageIndex)
        {
            _newPageIndex = newPageIndex;
        }

    }

}